<template>
  <div class="tw-datasetchart" ref="chart" :style="{height: mapHeight, width: mapWidth, backgroundColor: bgColor}">
    <div style="position:relative;width:100%;height:100%">
        <div class="m-school-map" id="map" ref="scatterMap" :style="{height: mapHeight, width: mapWidth, backgroundColor: bgColor}"></div>
        <div style="position: absolute;top:0;left:0;" :style="{height: mapHeight, width: mapWidth, backgroundColor: '#0b0d9d'}" v-if="maphidden!=='transparent'">
        </div>
        <div v-if="parentInfo.length>0&&parentInfo[parentInfo.length-1].level!=='district'" style="position: absolute;top: 20px;right: 20px;cursor: pointer;padding: 2px 8px;border: 1px solid #0469f1;z-index:9;border-radius: 5px;color: #00a7fe;"  @click="backtop">返回上一级</div>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import AMapLoader from '@amap/amap-jsapi-loader'
let map = null
let myChart = null

export default {
  name: 'chart-map',

  data () {
    return {
      maphidden: 'transparent',
      mmmData: [],
      // height: '895px',
      // width: '650px',
      bgColor: 'transparent',
      colors: [
        '#657df5',
        '#ffb336',
        '#4ac7ff',
        '#2bd3bd',
        '#96e388',
        '#fecd63'
      ],
      parentJson: null,
      parentInfo: [],
      curAreaId: 330400,
      mapCode: [],
      curLabName: '全部教育'
    }
  },
  props: {
    // mmmData: {
    //   type: Array,
    //   default: () => {
    //     return [
    //       {
    //         'name': 430100,
    //         'value': [
    //           {
    //             'name': '长沙市第一中学2',
    //             'value': [113.062178, 28.370502, 8, 999]
    //           }
    //         ]
    //       }]
    //   }
    // },
    clickDown: {
      type: Boolean,
      default: true
    },
    mapHeight: {
      type: String,
      default: '895px'
    },
    mapWidth: {
      type: String,
      default: '650px'
    },
    mapSchool: {
      type: Function,
      default: null
    }
  },
  computed: {

  },

  methods: {

    searchCity (adcode) {
      let vm = this
      if (myChart) {
        myChart.dispose()
      }
      if (adcode === 100000) { // 最顶部清空
        vm.parentInfo = []
      }
      vm.maphidden = '#031532'
      AMapLoader.load({
        'key': '4daa78d371fcbec403897e8ccc0c408c', // 申请好的Web端开发者Key，首次调用 load 时必填
        'version': '1.4.15', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        'plugins': ['Map3D', 'ElasticMarker', 'AMap.DistrictSearch', 'AMap.ControlBar', 'AMap.Heatmap'], // 插件列表
        'AMapUI': { // 是否加载 AMapUI，缺省不加载
          'version': '1.1' // AMapUI 缺省 1.1
          // 'plugins': [] // 需要加载的 AMapUI ui插件
        },
        'Loca': { // 是否加载 Loca， 缺省不加载
          'version': '1.3.2' // Loca 版本，缺省 1.3.2
        }
      }).then((AMap) => {
        map = new AMap.Map('map', {
          resizeEnable: false,
          showEffectOn: 'emphasis',
          // center: [116.30946, 39.937629], // 嘉兴市
          center: [114.197258,34.419372], // 尉氏县
          zoom: 12
        })
        AMapUI.loadUI(['geo/DistrictExplorer'], DistrictExplorer => {
          let districtExplorer = (window.districtExplorer = new DistrictExplorer({
            eventSupport: true, // 打开事件支持
            map: map
          }))
          districtExplorer.loadAreaNode(adcode, (error, areaNode) => {
            if (error) {
              console.error(error)
              return
            }

            // 这里判断一下
            let Json = areaNode.getSubFeatures()
            let plength = vm.parentInfo.length
            // 在同级上下钻再返回再下钻继续返回，应该只添加一个父级
            if (Json.length > 0 && !(plength > 0 && vm.parentInfo[plength - 1].cityCode === adcode)) {
              vm.parentInfo.push({
                cityCode: adcode,
                level: Json[0].properties.level // province, city, district
              })
            }
            // console.log('parentInfo', this.parentInfo)
            // 说明当前是市级别了,将这个值存起来
            if (Json.length > 0 && Json[0].properties.level === 'district') {
              vm.parentJson = Json
            } else if (Json.length === 0) { // 说明当前是县级
              if (this.parentJson.length === 0) {
                return
              }
              Json = vm.parentJson.filter(item => {
                if (item.properties.adcode === adcode) {
                  return item
                }
              })
              if (Json.length === 0) return
            }

            // 获取地图数据
            vm.getMapData(Json)
          })
        })
      }).catch(e => {
      })
      // this.maphidden = vm.bgColor
    },
    // 根据学段获取对应学校
    getMapNewData (labName) {
      this.curLabName = labName
      if (this.curAreaId !== 330400) {
        // 选择了区之后进行学段的划分
        let Json = this.parentJson.filter(item => {
          if (item.properties.adcode === this.curAreaId) {
            return item
          }
        })
        this.getMapData(Json, labName)
      } else {
        this.getMapData(this.parentJson, labName)
      }
    },
    getMapData (Json, labName) {
      // 这里我们模拟数据进行数据获取
      // 实际项目中会调接口把坐标和值返回来
      // 必须将数据写成数组对象格式,name,value是必须参数，后面的根据自己实际情况自定义添加
      // 除了name和value,其他的名字可以随便取
      // 分布图不需要坐标就可以实现，只需要名字和地图行政区的名字对应上了就行
      let vm = this

      if (vm.mapCode.length === 0 && vm.curAreaId === 330400) {
        Json.forEach(item => {
          vm.mapCode.push({
            adcode: item.properties.adcode,
            name: item.properties.name
          })
        })
      }
      // console.log(vm.mapCode)
      let mapData = Json.map(item => {
        return ({
          name: item.properties.name,
          value: Math.random() * 1000,
          level: item.properties.level,
          cityCode: item.properties.adcode
        })
      })

      let scatterData = []
      let mapJson = {}
      // geoJson必须这种格式
      mapJson.features = Json

      let name = ''
      if (this.curAreaId === 330400) {
        name = ''
      } else {
        let a = vm.mapCode.filter(itm => itm.adcode === this.curAreaId)
        if (a.length > 0) {
          name = a[0].name
        }
      }

      this.mapInit(name, labName).then(() => {
        let aaa = this.mmmData.filter(itm => itm.name === this.curAreaId)
        if (aaa.length > 0) {
          scatterData = aaa[0].value
        } else {
          scatterData = this.mmmData.filter(itm => itm.name === 330400)[0].value
        }

        this.initEchartsMap(scatterData, mapData, mapJson).then(() => {
          this.maohidden = 'transparent'
        })
      }).catch(() => {
        this.initEchartsMap(scatterData, mapData, mapJson).then(() => {
          this.maohidden = 'transparent'
        })
      })
    },
    async initEchartsMap (scatterData, mapData, mapJson) {
      let vm = this
      if (this.$refs.scatterMap) {
        myChart = echarts.init(this.$refs.scatterMap)
      } else {
        return
      }

      // 注册地图,前面名字自定义,后面是高德获取的geoJson
      echarts.registerMap('Map', mapJson)
      // 这里要加true表示重新绘制,不然下钻或筛选后,地图会飞出去
      await myChart.setOption({
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: p => {
            let txtCon = "<div style='text-align:center'>" + p.name + '</div>'
            return txtCon
          }
        },
        geo: {
          map: 'Map',
          roam: true,
          zoom: 1.1,
          // left: '150',
          itemStyle: { // 地图区域的多边形 图形样式
            // color: 'rgba(209,250,12,0.5)',
            normal: { // 是图形在默认状态下的样式
              color: '#0331aa',
              label: {
                show: true, // 是否显示标签
                textStyle: {
                  color: '#fff'
                }
              },

              borderWidth: 1,
              borderColor: '#88d2ff',
              shadowColor: '#657df5',

              shadowBlur: 3
            }
          },
          label: {
            show: true,
            textStyle: {
              color: '#fff',
              fontSize: 16
            }
          },
          emphasis: {
            itemStyle: {
              color: '#1890ff'
            },
            label: {
              show: true,
              color: '#fff'
            }
          }
        },
        series: [
          {
            name: '地图',
            type: 'map',
            geoIndex: 0,
            map: 'Map',
            roam: true, // 是否可缩放
            zoom: 1.1, // 缩放比例
            data: mapData,
            itemStyle: {
              normal: {
                show: true,
                areaColor: 'rgba(0,0,0,0)',
                borderColor: 'rgb(185, 220, 227)',
                borderWidth: '1'
              }
            },
            label: {
              normal: {
                show: true, // 显示省份标签
                textStyle: {
                  color: '#fff', // "rgb(249, 249, 249)", //省份标签字体颜色
                  fontSize: 16
                }
              },
              emphasis: {
              // 对应的鼠标悬浮效果
                show: true,
                textStyle: {
                  color: '#000'
                }
              }
            }
          },
          {
            name: '散点',
            // roam: true,
            zoom: 1.1,
            type: 'effectScatter',
            coordinateSystem: 'geo',
            data: scatterData,
            showEffectOn: 'emphasis',
            rippleEffect: {
              brushType: 'stroke'
            },
            hoverAnimation: false,
            zlevel: 1,
            symbolSize: function (val) {
              if (vm.curAreaId === 330400) {
                return 5
              } else {
                return 8
              }
            },
            label: {
              normal: {
                formatter: '{b}',
                position: 'right',
                show: false
              },
              emphasis: {
                show: false
              }
            },
            itemStyle: {
              normal: {
                color: '#ffea92'
              }
            }
          },
          {
            type: 'scatter',
            coordinateSystem: 'geo',
            data: [{
              name: '嘉兴市教育局',
              value: [120.79192, 30.73647]
            }],
            // encode: {
            //   value: 2
            // },
            zlevel: 2,
            symbolSize: 25,
            symbol: 'image://',
            symbolRotate: 0,
            itemStyle: {
              color: '#F06C00'
            },
            emphasis: {
              label: {
                show: false
              }
            }
          }]
      }, true)
      myChart.hideLoading()
      this.maphidden = 'transparent'
      // 点击前解绑，防止点击事件触发多次
      if (vm.clickDown) {
        myChart.off('click')
        myChart.on('click', this.clickMap)
      }
    },
    // 这里有个参数，就是点击的那个地块的数据信息
    clickMap (params) {
      // 如果当前是最后一级，那就直接return
      if (params.componentType === 'geo') { // 选中区域
      } else if (params.componentType === 'series') { // 选中学校
        if (params.componentSubType === 'map') { // 选中区域
          let data = params.data
          //  调用父组件的方法重新定位当前区域的学校散点
          // this.mapInit(data.name)
          if (data.level === 'district') {
            if (this.curAreaId !== data.cityCode) {
              this.curAreaId = data.cityCode
              let Json = this.parentJson.filter(item => {
                if (item.properties.adcode === data.cityCode) {
                  return item
                }
              })
              this.getMapData(Json, this.curLabName)
            }

            if (this.parentInfo.length > 0 && this.parentInfo[this.parentInfo.length - 1].level === 'district') {
              this.parentInfo.push({
                cityCode: data.cityCode,
                level: 'xiangzhen'
              })
            }
          } else {
            this.searchCity(data.cityCode)
          }

          this.getSchoolData(params)
        } else if (params.componentSubType === 'effectScatter') { // 选中学校
          if (this.curAreaId !== 330400) {
            this.getSchoolData(params)
          }
        }
      }
    },
    backtop () {
      this.$emit('getSchoolData', '', this.curLabName)
      if (this.parentInfo.length > 1) {
        let data = this.parentInfo.pop()
        this.curAreaId = this.parentInfo[this.parentInfo.length - 1].cityCode
        if (data.level === 'xiangzhen') {
          this.getMapData(this.parentJson, this.curLabName)
        } else {
          this.searchCity(this.curAreaId)
        }
      } else {
        this.searchCity(100000)
      }
    },
    getSchoolData (params) {
      this.$emit('getSchoolData', params, this.curLabName)
    },
    getCodeData (data) {
      this.$emit('getCodeData', data)
    },

    // 学校地图数据
    async mapInit (name, jyjdname = '全部教育') {
      let cityNam = name || ''
      let newListCond = []
      if (jyjdname === '全部教育') {
        newListCond = cityNam ? [{
          fieldName: 'szqy',
          operator: 'IN',
          fieldValues: [cityNam],
          prepender: 'AND'
        }, {
          fieldName: 'tjnf',
          operator: 'IN',
          fieldValues: ['2019'],
          prepender: 'AND'
        }] : [ {
          fieldName: 'tjnf',
          operator: 'IN',
          fieldValues: ['2019'],
          prepender: 'AND'
        }] // 有统计年份
      } else {
        newListCond = cityNam ? [{
          fieldName: 'jyjd',
          operator: 'IN',
          fieldValues: [jyjdname],
          prepender: 'AND'
        }, {
          fieldName: 'szqy',
          operator: 'IN',
          fieldValues: [cityNam],
          prepender: 'AND'
        }, {
          fieldName: 'tjnf',
          operator: 'IN',
          fieldValues: ['2019'],
          prepender: 'AND'
        }] : [{
          fieldName: 'jyjd',
          operator: 'IN',
          fieldValues: [jyjdname],
          prepender: 'AND'
        }, {
          fieldName: 'tjnf',
          operator: 'IN',
          fieldValues: ['2019'],
          prepender: 'AND'
        }] // 有统计年份
      }
      // var newListCond = cityNam ? [{ fieldName: 'szqy', operator: 'IN', fieldValues: [cityNam], prepender: 'AND' }] : [] // 无统计年份
      let data = {
        'pagination': {
          'calTotal': true,
          'numPerPage': 1000,
          'pageNo': 1,
          'start': 0,
          'startNum': -1
        },
        conditions: newListCond
      }
      await this.$axios.post(`/tw-cloud-datatheme-server/themedata/app_xxxx_xxwzxx`, data).then(resp => {
        let {pageInfo, serverResult} = resp.data
        if (serverResult.resultCode === '200') {
          let mmDataList = [{
            name: 330400,
            value: []
          }]
          pageInfo.list.forEach(el => {
            mmDataList[0].value.push({
              'name': el.xxmc,
              'value': [el.wd - 0, el.jd - 0, 8, 999],
              jgid: el.jgid
            })
          })
          this.mmmData = mmDataList
          // this.searchCity(this.curAreaId)
        }
      }).catch(resp => {
        console.log(resp)
      })
    }
  },

  mounted () {
    let vm = this
    this.$nextTick(() => {
      vm.searchCity(330400)
    })

    // window.addEventListener('resize', this.resize)
  },

  beforeDestroy () {
    if (myChart) {
      myChart.dispose()
      myChart = null
    }
    if (map) {
      map.destroy()
      map = null
    }
    // window.removeEventListener('resize', this.resize)
  }
}
</script>

<style lang="scss">
 .tw-datasetchart {
  width: 100%;
  height: 600px;
}

.tw-datasetchart-chartbox {
  display: block;
  width: 100%;
  height: 100%;
}

.m-school-map {
  background-color: transparent !important;
}
</style>
